package com.lagou.service.impl;

import com.lagou.dao.AuthCodeDao;
import com.lagou.pojo.AuthCode;
import com.lagou.service.CodeService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;

import java.util.Date;
import java.util.List;

@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    private AuthCodeDao authCodeDao;

    @Override
    public Integer addCode(String email, String code) {

        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        authCode.setCreatetime(new Date());
        authCode.setExpiretime(new Date(authCode.getCreatetime() .getTime() + 600000));

        authCode = authCodeDao.save(authCode);

        return 1;
    }

    @Override
    public Integer validateCode(String email, String code) {

        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);

        Sort sort = new Sort(Sort.Direction.DESC,"expiretime");

        Example<AuthCode> example = Example.of(authCode);

        List<AuthCode> list = authCodeDao.findAll(example,sort);

        if(list == null || list.size() == 0){
            return 1;
        }

        Date expiretime = list.get(0).getExpiretime();
        Date now = new Date();

        System.out.println(now);

        if(expiretime.getTime() > now.getTime()){
            return 0;
        }else{
            return 2;
        }

    }
}
